import React, { useRef, useState } from 'react';
import { router, Text, Image, View, ScrollView, publishDps, Button, showToast } from '@ray-js/ray';
import { Card } from '@/components/card';
import { IconFont, Empty } from '@/components';
import Strings from '@/i18n';
import {
  CellGroup,
  Cell,
  Switch,
  SwipeCell,
  ActionSheet,
  DateTimePicker,
  Picker,
} from '@ray-js/smart-ui';
import { useDevice, useProps } from '@ray-js/panel-sdk';
import { useAppConfig } from '@/hooks/useAppConfig';
import { NavBarCustom } from '@/components/NavBarCustom';

import res from '@/res/image';
import { getCachedSystemInfo } from '@/api/getCachedSystemInfo';

import { decodeClear, decodeDisinfect, encodeClear, encodeDisinfect } from '@/utils/parse';
import styles from './index.module.less';

import clsx from 'clsx';

const { safeArea } = getCachedSystemInfo();

const { height } = safeArea;

const max = 10;

const getTimeMeasureUtils = (time: {
  hour: number;
  minute: number;
  duration: number;
  status: boolean;
}) => {
  if (time.hour === undefined) {
    return '';
  }

  const { hour, minute } = time;

  return `${hour < 10 ? `0${hour}` : hour}:${minute < 10 ? `0${minute}` : minute}`;
};

const getDurationMeasureUtils = (
  time: {
    hour: number;
    minute: number;
    duration: number;
    status: boolean;
  } | null
) => {
  if (time.duration === undefined) {
    return '';
  }

  const { duration } = time;

  return `${duration}min`;
};

export function SterillizationSchedule() {
  const [delShow, setDelShow] = useState(false);

  const [addShow, setAddShow] = useState(false);

  const { clean_onoff_time: cleanOnOffTime } = useProps();

  const cleanList = decodeClear(cleanOnOffTime);

  const currentRef = useRef<number>(0);

  const [addTime, setAddTime] = useState({
    hour: 12,
    minute: 0,
  } as any);

  // const
  return (
    <View className={styles.view}>
      <NavBarCustom name={Strings.getLang('cleanSchedule')} back />
      <View className={styles.pageTips}>
        <Text>{Strings.getLang('cleanScheduleTips')}</Text>
      </View>
      {cleanList?.length ? (
        <ScrollView
          className={styles.scrollView}
          scrollY
          refresherTriggered
          style={{
            height: `calc(${height}px - env(safe-area-inset-bottom) - env(safe-area-inset-top) - 100rpx)`,
          }}
        >
          (
          <View className={styles.cellGroup}>
            {cleanList.map((item, index) => (
              <View
                key={index}
                className={styles.item}
                onLongPress={() => {
                  currentRef.current = index;
                  setDelShow(true);
                }}
              >
                <View className={styles.time}>
                  <Text className={styles.timeText}>{`${
                    item.hour < 10 ? `0${item.hour}` : item.hour
                  }:${item.minute < 10 ? `0${item.minute}` : item.minute}`}</Text>
                </View>
                <Switch
                  checked={item.status}
                  onChange={v => {
                    const str = encodeClear(
                      cleanList.map((item, i) => ({
                        ...item,
                        status: i === index ? !item.status : item.status,
                      }))
                    );

                    publishDps({
                      clean_onoff_time: str,
                    });
                  }}
                />
              </View>
            ))}
          </View>
          )
        </ScrollView>
      ) : (
        <Empty handleAddTiming={() => setAddShow(true)} />
      )}

      {cleanList?.length ? (
        <View className={styles.addButtonBox}>
          <Button
            className={clsx(styles.addButton, cleanList.length >= max && styles.disabledBtn)}
            disabled={cleanList.length >= max}
            onClick={() => {
              setAddShow(true);
            }}
          >
            {Strings.getLang('add')}
          </Button>
        </View>
      ) : null}

      <ActionSheet show={delShow} onCancel={() => setDelShow(false)}>
        <View className={styles.content}>
          <View className={styles.titleText}>
            <Text>{Strings.getLang('cleanSchedule')}</Text>
          </View>
          <View className={styles.tipsText}>
            <Text>{Strings.getLang('cleanScheduleDelTips')}</Text>
          </View>

          <View className={styles.buttonGroup}>
            <Button className={styles.button} onClick={() => setDelShow(false)}>
              {Strings.getLang('cancel')}
            </Button>
            <Button
              className={styles.button}
              onClick={() => {
                const newList = cleanList.filter((item, index) => index !== currentRef.current);
                const str = encodeClear(newList);

                publishDps({
                  clean_onoff_time: str,
                });

                setDelShow(false);
              }}
            >
              {Strings.getLang('confirm')}
            </Button>
          </View>
        </View>
      </ActionSheet>
      <ActionSheet show={addShow} onCancel={() => setAddShow(false)}>
        <View className={styles.content}>
          <View className={styles.editTitle}>{Strings.getLang('cleanScheduleAddTitle')}</View>
          <View className={styles.pickerBox}>
            <View className={styles.timePickerBox}>
              <DateTimePicker
                type="time"
                value="12:00"
                showToolbar={false}
                onInput={v => {
                  const hour = (v.detail as string).split(':')[0];
                  const minute = (v.detail as string).split(':')[1];
                  setAddTime({
                    hour: Number(hour),
                    minute: Number(minute),
                  });
                }}
                locale={{
                  hour: Strings.getLang('hour'),
                  minute: Strings.getLang('minute'),
                }}
              />
            </View>
          </View>
          <View className={styles.buttonGroup}>
            <Button className={styles.button} onClick={() => setDelShow(false)}>
              {Strings.getLang('cancel')}
            </Button>
            <Button
              className={styles.button}
              onClick={() => {
                if (
                  cleanList.some(
                    item => item.hour === addTime.hour && item.minute === addTime.minute
                  )
                ) {
                  showToast({
                    icon: 'none',
                    title: Strings.getLang('cleanScheduleSameTips'),
                  });
                  return;
                }

                const newList = [
                  ...cleanList,
                  {
                    ...addTime,
                    status: true,
                  },
                ];
                console.log(`🚀 ~ newList:`, newList);
                const str = encodeClear(newList);

                publishDps({
                  clean_onoff_time: str,
                });

                setAddShow(false);
              }}
            >
              {Strings.getLang('confirm')}
            </Button>
          </View>
        </View>
      </ActionSheet>
    </View>
  );
}

export default SterillizationSchedule;
